/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef INCLUDE_RULE_ID_MANAGER_H
#define INCLUDE_RULE_ID_MANAGER_H

#include <cstdint>
#include<vector>
#include <map>
#include <mutex>

namespace OHOS {
namespace nmd {

typedef struct {
    bool used;
    bool deleted;
    int32_t ruleId;
} RuleIdStatus;

class RuleIdManager {
public:
    RuleIdManager();
    ~RuleIdManager() = default;

    enum RuleType {
        RULE_LEVEL_VPN_OUTPUT_TO_LOCAL,
        RULE_LEVEL_SECURE_VPN,
        RULE_LEVEL_EXPLICIT_NETWORK,
        RULE_LEVEL_OUTPUT_IFACE_VPN,
        RULE_LEVEL_VPN_ALL,
        ROUTE_VPN_NETWORK_TABLE
    };

    /**
     * Init Rule start id
     *
     * @return Returns 0, init start, otherwise it will fail
     */
    static int32_t Init();

    /**
     * Init Rule id
     *
     * @param type id type
     * @param startId start rule id
     * @param maxCount rule id count
     * @return Returns 0, init start, otherwise it will fail
     */
    static int32_t InitRuleIds(RuleType type, int32_t startId, int32_t maxCount);

    /**
     * Get next rule id
     *
     * @param type id type
     * @return Returns rule id
     */
    static int32_t GetNextRuleId(RuleType type);

    /**
     * Delete Rule id
     *
     * @param type id type
     * @param num remove rule id
     * @return Returns 0, remove successfully, otherwise it will fail
     */
    static int32_t DeleteRuleId(RuleType type, int32_t num);

private:
    static std::vector<RuleIdStatus> ruleLevelVpnOutputToLocal_;
    static std::vector<RuleIdStatus> ruleLevelSecureVpn_;
    static std::vector<RuleIdStatus> ruleLevelExplicitNetwork_;
    static std::vector<RuleIdStatus> ruleLevelOutputIfaceVpn_;

    static std::mutex vpnRuleIdLock_;
    static std::map<RuleType, uint32_t> vpnRuleId_;
    static std::map<RuleType, uint32_t> vpnRuleMaxCount_;

    static int32_t AddRuleId(RuleType type, int32_t startId, int32_t maxCount);
    static int32_t InitRuleIds(RuleType type, std::vector<RuleIdStatus>& ruleIds);
    static int32_t GetNextRuleId(RuleType type, std::vector<RuleIdStatus>& ruleIds);
    static int32_t DeleteRuleId(RuleType type, std::vector<RuleIdStatus>& ruleIds, int32_t num);

    static int32_t GetStartRuleId(RuleType type);
    static int32_t GetRuleIdMaxCount(RuleType type);
};
} // namespace nmd
} // namespace OHOS
#endif // INCLUDE_RULE_ID_MANAGER_H
